/**
 * @author mashaodong
 * @class 对腾讯音视频做一层封装
 */

import TRTC from "trtc-js-sdk";
import { callableFuns } from "./callback";
import getConfig from "./config";
import ImTim from "./imIndex";
import {
  getCreateClientParams,
  getCreateStreamParams,
  getJoinParams,
  removeYour,
} from "./utils";
import { joinRoomError, leaveRoomError } from "./error";

export default class TrtcVideoCall extends ImTim {
  constructor(options) {
    super();
    this.joinStaus = false;
    this.localStream = null;
    this.userId = options.userId;
    this.roomId = options.roomId;
    this.myVideo = options.myVideo;
    this.yourUserIds = [];
    this.yourVideosBox = [options.yourVideo1, options.yourVideo2];
    this.config = getConfig(this.userId);
    this.getAccept = options.getAccept;
    this.timGroupID = options.timGroupID;
    this.getTimGroupID = options.getTimGroupID;
    this.init();
  }
  dataInit() {
    this.joinStaus = false;
    this.localStream = null;
    this.userId = null;
    this.roomId = null;
    this.myVideo = null;
    this.yourUserIds = [];
    this.yourVideosBox = [];
    this.getAccept = null;
    this.timGroupID = null;
    this.getTimGroupID = null;
  }
  async init() {
    await this.createClient();
    await this.createStream();
  }
  async createClient() {
    // 创建一个实时音视频通话的客户端对象
    this.client = TRTC.createClient(getCreateClientParams.call(this));
    // 所有的回调函数
    callableFuns.call(this);
  }
  async createStream() {
    if (!joinRoomError.call(this)) {
      return;
    }
    // 加入一个音视频通话房间。
    await this.join();
    // 创建一个本地流 Stream 对象
    this.localStream = TRTC.createStream(getCreateStreamParams.call(this));
    // 初始化本地音视频流对象
    this.initialize();
  }
  // 加入一个音视频通话房间。
  async join() {
    await this.client.join(getJoinParams.call(this));
  }
  async initialize() {
    // 初始化本地音视频流对象
    await this.localStream.initialize();
    // 发布本地音视频流
    await this.publish();
  }
  async play() {
    await this.localStream.play(this.myVideo);
    // IM登录
    this.timLogin({ userId: this.userId, config: this.config });
    this.joinStaus = true;
  }
  // 发布本地音视频流
  async publish() {
    await this.client.publish(this.localStream);
    // 播放该音视频流
    this.play();
  }
  // 退出当前音视频通话房间
  async leave() {
    if (!leaveRoomError.call(this)) {
      return;
    }
    await this.timQuitGroup(this.timGroupID);
    await this.unpublish();
    await this.client.leave();
    // 停止播放音视频流
    this.localStream.stop();
    // 关闭音视频流，释放摄像头和麦克风访问权限。
    this.localStream.close();
    removeYour.call(this);
    this.dataInit();
  }
  // 取消发布本地流
  async unpublish() {
    await this.client.unpublish(this.localStream);
  }
}
